<template>
  <div class="cart-container">
    <div class="cart-header">
      <h1 class="cart-title">我的购物车</h1>
      <div class="cart-summary">
        <span class="cart-count">已选 {{ selectedCount }} 件商品</span>
        <span class="cart-total">总计: <em>￥{{ totalPrice.toFixed(2) }}</em></span>
      </div>
    </div>

    <div class="cart-content">
      <div class="cart-items">
        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>

        <div v-else-if="error" class="error-state">
          <p>{{ error }}</p>
          <button @click="fetchCartList" class="retry-btn">重试</button>
        </div>

        <template v-else>
          <div class="cart-toolbar">
            <label class="select-all">
              <input type="checkbox" v-model="selectAll" @change="handleSelectAll">
              全选
            </label>
            <button class="clear-selected-btn" @click="clearSelected">删除选中商品</button>
          </div>

          <div v-if="cartItems.length === 0" class="empty-cart">
            <img src="../assets/images/empty-cart.png" alt="空购物车" class="empty-cart-img">
            <p class="empty-cart-text">购物车还是空的</p>
            <router-link to="/" class="continue-shopping-btn">去购物</router-link>
          </div>

          <div v-else>
            <div class="cart-item" v-for="item in cartItems" :key="item.id">
              <div class="item-select">
                <input type="checkbox" v-model="item.selected" @change="updateSelectAll">
              </div>
              <div class="item-image">
                <img :src="item.image" :alt="item.name">
              </div>
              <div class="item-info">
                <h3 class="item-name">{{ item.name }}</h3>
              </div>
              <div class="item-price">
                <span class="price">￥{{ item.price.toFixed(2) }}</span>
              </div>
              <div class="item-quantity">
                <button class="quantity-btn" @click="decreaseQuantity(item)" :disabled="item.quantity <= 1">-</button>
                <input type="number" v-model.number="item.quantity" min="1" @change="validateQuantity(item)">
                <button class="quantity-btn" @click="increaseQuantity(item)">+</button>
              </div>
              <div class="item-total">
                <span>￥{{ (item.price * item.quantity).toFixed(2) }}</span>
              </div>
              <div class="item-actions">
                <button class="remove-btn" @click="removeItem(item.id)">
                  <el-icon><Delete /></el-icon>
                </button>
              </div>
            </div>
          </div>
        </template>
      </div>

      <div class="cart-sidebar">
        <div class="cart-card">
          <div class="cart-card-header">
            <h3>订单摘要</h3>
          </div>
          <div class="cart-card-body">
            <div class="summary-item">
              <span>商品总额</span>
              <span>￥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <div class="summary-item">
              <span>运费</span>
              <span>￥0.00</span>
            </div>
            <div class="summary-item total">
              <span>应付总额</span>
              <span>￥{{ totalPrice.toFixed(2) }}</span>
            </div>
          </div>
          <div class="cart-card-footer">
            <button class="checkout-btn" :disabled="selectedCount === 0" @click="goToCheckout">
              去结算 ({{ selectedCount }})
            </button>
            <button class="clear-cart-btn" @click="handleClearCart">清空购物车</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCartList, addToCart, removeFromCart, clearCart as clearCartApi, subtractCartQuantity } from '../../axios/cart'
import { ElMessage } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

const router = useRouter()
const cartItems = ref([])
const loading = ref(false)
const error = ref(null)
const selectAll = ref(false)

// 获取购物车列表
const fetchCartList = async () => {
  loading.value = true
  error.value = null
  try {
    const response = await getCartList()
    if (response.code === 1) {
      cartItems.value = response.data.map(item => ({
        id: item.id,
        productId: item.productId,
        name: item.productName,
        image: item.productImage || 'https://via.placeholder.com/120', // 使用默认图片
        price: item.unitPrice,
        quantity: item.quantity,
        selected: false
      }))
    } else {
      error.value = response.msg || '获取购物车列表失败'
    }
  } catch (err) {
    error.value = '获取购物车列表失败，请稍后重试'
    console.error('获取购物车列表失败:', err)
  } finally {
    loading.value = false
  }
}

// 删除商品
const removeItem = async (productId) => {
  try {
    const response = await removeFromCart([productId]) // 传数组
    if (response.code === 1) {
      cartItems.value = cartItems.value.filter(item => item.id !== productId)
      ElMessage.success('商品已删除')
    } else {
      ElMessage.error(response.msg || '删除商品失败')
    }
  } catch (err) {
    ElMessage.error('删除商品失败，请稍后重试')
    console.error('删除商品失败:', err)
  }
}

// 清空购物车
const handleClearCart = async () => {
  if (!confirm('确定要清空购物车吗？')) return
  try {
    const response = await clearCartApi()
    if (response.code === 1) {
      cartItems.value = []
      ElMessage.success('购物车已清空')
    } else {
      ElMessage.error(response.msg || '清空购物车失败')
    }
  } catch (err) {
    ElMessage.error('清空购物车失败，请稍后重试')
    console.error('清空购物车失败:', err)
  }
}

// 计算选中商品的总价
const totalPrice = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => total + item.price * item.quantity, 0)
})

// 计算选中商品的数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length
})

// 去结算
const goToCheckout = () => {
  if (selectedCount.value === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  
  // 获取选中的商品，并确保包含所有必要的字段
  const selectedItems = cartItems.value
    .filter(item => item.selected)
    .map(item => ({
      id: item.productId, // 使用 productId 作为商品ID
      name: item.name,
      image: item.image,
      price: item.price,
      quantity: item.quantity
    }))
  
  // 将选中的商品数据作为参数传递到订单页面
  router.push({
    path: '/order',
    query: {
      items: JSON.stringify(selectedItems)
    }
  })
}

// 页面加载时获取购物车列表
onMounted(() => {
  fetchCartList()
})

// 处理全选
const handleSelectAll = () => {
  cartItems.value.forEach(item => {
    item.selected = selectAll.value
  })
}

// 更新全选状态
const updateSelectAll = () => {
  selectAll.value = cartItems.value.every(item => item.selected)
}

// 增加数量
const increaseQuantity = async (item) => {
  try {
    const response = await addToCart({
      productId: item.productId,
    })
    if (response.code === 1) {
      item.quantity += 1
      ElMessage.success('数量已更新')
    } else {
      ElMessage.error(response.msg || '增加数量失败')
    }
  } catch (err) {
    ElMessage.error('增加数量失败，请稍后重试')
    console.error('增加数量失败:', err)
  }
}

// 减少数量
const decreaseQuantity = async (item) => {
  if (item.quantity <= 1) return
  try {
    const response = await subtractCartQuantity(item.productId)
    if (response.code === 1) {
      item.quantity -= 1
      ElMessage.success('数量已更新')
    } else {
      ElMessage.error(response.msg || '减少数量失败')
    }
  } catch (err) {
    ElMessage.error('减少数量失败，请稍后重试')
    console.error('减少数量失败:', err)
  }
}

// 验证数量
const validateQuantity = (item) => {
  if (item.quantity < 1) {
    item.quantity = 1
  }
}

// 删除选中商品
const clearSelected = async () => {
  const selectedItems = cartItems.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请先选择要删除的商品')
    return
  }
  const ids = selectedItems.map(item => item.id)
  try {
    const response = await removeFromCart(ids)
    if (response.code === 1) {
      cartItems.value = cartItems.value.filter(item => !item.selected)
      ElMessage.success('选中商品已删除')
    } else {
      ElMessage.error(response.msg || '批量删除失败')
    }
  } catch (err) {
    ElMessage.error('批量删除失败，请稍后重试')
    console.error('批量删除失败:', err)
  }
  selectAll.value = false
}
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.cart-header {
  margin-bottom: 30px;
}

.cart-title {
  font-size: 28px;
  color: #2c3e50;
  margin-bottom: 15px;
}

.cart-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
}

.cart-total em {
  color: #e74c3c;
  font-style: normal;
  font-size: 20px;
  font-weight: bold;
}

.cart-content {
  display: grid;
  grid-template-columns: 1fr 350px;
  gap: 30px;
}

.cart-items {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.cart-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.select-all {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.select-all input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.clear-selected-btn {
  padding: 8px 16px;
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 6px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
}

.clear-selected-btn:hover {
  background: #e9ecef;
}

.cart-item {
  display: grid;
  grid-template-columns: 50px 120px 1fr 100px 120px 100px 50px;
  gap: 15px;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
  transition: all 0.3s ease;
}

.cart-item:hover {
  background: #f8f9fa;
}

.item-select {
  display: flex;
  align-items: center;
}

.item-select input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.item-image {
  width: 120px;
  height: 120px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.item-image:hover {
  transform: scale(1.05);
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.item-name {
  font-size: 20px;
  color: #2c3e50;
  margin: 0;
  font-weight: 600;
  transition: color 0.3s ease;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-name:hover {
  color: #4CAF50;
}

.item-price {
  color: #e74c3c;
  font-weight: bold;
  font-size: 18px;
  text-align: right;
  padding-right: 10px;
}

.item-quantity {
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: center;
  min-width: 120px;
}

.quantity-btn {
  width: 28px;
  height: 28px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  font-size: 16px;
  flex-shrink: 0;
}

.quantity-btn:hover:not(:disabled) {
  background: #f8f9fa;
}

.quantity-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.item-quantity input {
  width: 40px;
  height: 28px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
  font-size: 14px;
  flex-shrink: 0;
}

.item-total {
  color: #e74c3c;
  font-weight: bold;
  font-size: 18px;
  text-align: right;
  padding-right: 10px;
}

.remove-btn {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
}

.remove-btn:hover {
  color: #e74c3c;
}

.empty-cart {
  text-align: center;
  padding: 40px 0;
}

.empty-cart-img {
  width: 200px;
  margin-bottom: 20px;
}

.empty-cart-text {
  color: #666;
  margin-bottom: 20px;
}

.continue-shopping-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.3s;
  text-decoration: none;
  display: inline-block;
}

.continue-shopping-btn:hover {
  background: #45a049;
}

.cart-sidebar {
  position: sticky;
  top: 20px;
}

.cart-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.cart-card-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.cart-card-header h3 {
  margin: 0;
  color: #2c3e50;
}

.cart-card-body {
  padding: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  color: #666;
}

.summary-item.total {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
  font-weight: bold;
  color: #2c3e50;
}

.cart-card-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.checkout-btn, .clear-cart-btn {
  width: 100%;
  padding: 12px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.checkout-btn {
  padding: 15px 40px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.checkout-btn:hover:not(:disabled) {
  background: #45a049;
  transform: translateY(-2px);
}

.checkout-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.clear-cart-btn {
  background: #f8f9fa;
  color: #666;
}

.clear-cart-btn:hover {
  background: #e9ecef;
}

@media (max-width: 768px) {
  .cart-content {
    grid-template-columns: 1fr;
  }
  
  .cart-sidebar {
    position: static;
  }
  
  .cart-item {
    grid-template-columns: 1fr;
    gap: 8px;
    text-align: center;
    padding: 12px;
  }
  
  .item-image {
    margin: 0 auto;
  }
  
  .item-quantity {
    justify-content: center;
  }
  
  .item-actions {
    display: flex;
    justify-content: center;
  }

  .item-name {
    font-size: 18px;
  }

  .item-price, .item-total {
    font-size: 16px;
  }
}

.loading-state,
.error-state {
  text-align: center;
  padding: 40px 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #4CAF50;
  border-radius: 50%;
  margin: 0 auto 20px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.retry-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  margin-top: 10px;
}
</style> 